package com.qst.express.controller;


import com.qst.commonUtils.result.R;
import com.qst.commonUtils.user.IpAddrUtils;

import com.qst.express.service.EadminService;
import com.qst.express.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mjh
 * @since 2022-09-25
 */
@Api(description = "管理员模块")
@RestController
@RequestMapping("/express/eadmin")
@CrossOrigin
public class EadminController {

    @Autowired
    private EadminService eadminService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R login(@RequestBody(required = false) HashMap<String,String>  admin, HttpServletRequest request) {
        String username = admin.get("username");
        String password = admin.get("password");
        System.out.println(username + " ，" + password);

        boolean result = eadminService.login(username,password);
        if (result) {
            // 登录成功后操作
            // 1.更新登录时间的 和 ip 的更新
//            String ipAddr = IpAddrUtils.getIpAddr(request);
//            eadminService.updateLogin(username,ipAddr);
            //2. 存管理员手机号到session
            String adminPhone = eadminService.getAdminPhone(username);
            System.out.println("存入时管理员手机："+adminPhone);
            UserUtil.setAdminPhone(request.getSession(),adminPhone);
            String adminPhone2 = UserUtil.getAdminPhone(request.getSession());
            System.out.println("管理员手机号："+adminPhone2);
            //存管理员名字到session
            request.getSession().setAttribute("adminName",username);
            return R.ok().data("token","admin");
        }else {
            return R.error().message("登录失败");
        }

    }

    @ApiOperation(value = "登录信息")
    @RequestMapping("/info")
    public R info() {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        return R.ok().data("roles", "[admin]").data("name", "admin").data("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
    }

    //登出
    @ApiOperation("登出操作")
    @PostMapping("/logout")
    public R logout(){
        return R.ok();
    }
}

